/**
 * 添加自己音效：需要修改 2处 
 *      1、修改第 8 行代码（var maxWav=4;）当前数量+1即可
 *      2、在第 12 行的switch代码添加一个 case ；
 *              格式为（值 为上一个的+1）：case 值: name="文件夹名字（不要前缀 'wav_'）"; str="这里是介绍";break;
 *      补充：如果想修改默认选择。修改第 30 行代码的值为对应的 case的值 即可。
 */
var maxWav=16;//除了原音效，存在几种音效
function f5WavTip() {
    let str="";
    let name="";//文件夹名字 自动添加前缀 "wav_" 只要后缀
    let tag="<br>&nbsp;&nbsp;—— ";
    let kmTag=tag+"音频来自微信弦外小程序";
    switch (wavWay) {
        case 1: name="harp1"; str="竖琴模式"+tag+"游戏内录制，存在杂音";break;
        case 2: name="piano1"; str="钢琴模式"+tag+"游戏内录制，存在杂音";break;
        case 3: name="piano"; str="钢琴模式"+tag+"@𓇼（884593935） 大佬的音效";break;
        case 4: name="piano2"; str="钢琴模式"+tag+"@404（690818882） 大佬的游戏包中提取的音效";break;
        case 5: name="km_2_jideta"; str="吉的他"+kmTag; break;
        case 6: name="km_3_yindehe"; str="音的盒"+kmTag; break;
        case 7: name="km_4_bangbangbang"; str="棒棒棒！"+kmTag; break;
        case 8: name="km_5_weilaikeji"; str="未来科技"+kmTag; break;
        case 9: name="km_6_shuqin"; str="竖琴"+kmTag; break;
        case 10: name="km_7_muqin"; str="木琴"+kmTag; break;
        case 11: name="km_8_meng"; str="梦"+kmTag; break;
        case 12: name="km_9_di"; str="笛"+kmTag; break;
        case 13: name="km_10_8bite"; str="8比特"+kmTag; break;
        case 14: name="km_11_ruan"; str="阮"+kmTag; break;
        case 15: name="km_12_datiqin"; str="大提琴"+kmTag; break;
        case 16: name="km_13_wanjuyuedui"; str="玩具乐队"+kmTag; break;
        //case : name=""; str=""+tag+""; break;
        default:name="default"; str="默认模式"+tag+"@404 大佬的音效";break;
    }

    let audios=document.getElementById("wavPlayer").getElementsByTagName("audio");
    let len=audios[0].src.indexOf("wav_")+4;
    let prefix=audios[0].src.substring(0,len);
    for (let i = 0; i < audios.length; i++) {
        audios[i].src=prefix+name
                     +audios[i].src.substring(audios[i].src.lastIndexOf("/"));
    }
    document.getElementById("wavTip").innerHTML=str;
}
function rv(index) {
    wavWay = index;
    f5WavTip();
}
window.onload=function(){
    wavWay=4;//默认乐器模式
    audios=this.document.getElementsByName("audio");
    anyWay=0;
    delayDefault=10;
    f5WavTip();
    f5AnyTip();
}
var audios=null;
var anyWay=0;
var wavWay=0;
var maxAny=2;
var logPrint=true;
var delayDefault=10;
var anyData="";
var tag=false;
var volume=true;
var removeText=true;

function dieOut(e) {
    e.style.backgroundColor="blanchedalmond";
    if (e.innerHTML!="" || e.innerHTML!="undefined") {
        e.innerHTML=window.clearInterval(e.innerHTML);
    }
    let index = 100;
    e.innerHTML=window.setInterval(function(){
        if (index<0) {
            e.style.backgroundColor="rgba(255,235,205,0)";
            e.innerHTML=window.clearInterval(e.innerHTML);
        } else {
            e.style.backgroundColor="rgba(255,235,205, "+index/100+")";
            index-=5;
        }
    },20);
}


function start() {
    if(logPrint) console.log("开始执行...");
    tag=false;
    let datas=document.getElementById("data").value;
    if (anyWay==1) {
        datas=(scoreAny(datas));
    } else if (anyWay==2) {
        datas=(LiPuAny(datas));
    } else {
        let startLength=datas.indexOf("{");
        if (startLength>-1) {
            let endLength=datas.indexOf("}");
            if (endLength<0) {
                datas+="}";
            }
            datas = eval('(' + datas + ')')
            if (datas.hasOwnProperty("delay")) {
                delayDefault=datas.delay;
            }
            document.getElementById("delay").value=delayDefault;
            tag=true;
            console.log("添加前缀"+tag);
            anyData="{\"delay\":\"250\",\"musicData\":\"";
            datas=datas.musicData;
        }
        datas=datas;
    }
    datas=datas.split(/\s+/);
    if(logPrint) console.log("最终数据："+datas);
    analysis(datas);
    if(logPrint) console.log("执行结束");
}

function scoreAny(scoreData) {
    scoreData=(scoreData.split("|")[2]);
    
    var score = eval('(' + scoreData + ')').score;
    
    
    scoreData="";
    score.forEach((e)=>{
        
        var tempStr="";
        e.pitches.forEach((pitches)=>{
            if(pitches.indexOf(":")>-1){
                if(pitches=="1::"){
                    tempStr+="15";
                } else if(pitches=="-"){
                    if(logPrint) console.log("延迟");
                } else {
                    tempStr+=(parseInt(pitches)+7);
                }
            } else {
                tempStr+=pitches;
            }
            tempStr+=",";
        });
        scoreData+=tempStr.substring(0,tempStr.length-1)+" ";
        
        var tempDelay=0;
        if(e.duration.indexOf("+")){
            e.duration.split("+").forEach((e)=>{tempDelay+=parseInt(e);});
        } 
        scoreData+=( (32 / tempDelay) * 60)+"ms ";
    });
    return scoreData;
}

function LiPuAny(scoreData) {
    let funArray=["A1","A2","A3","A4","A5","A6","A7"
                 ,"B1","B2","B3","B4","B5","B6","B7","C1"]
    scoreData=scoreData.substring(scoreData.lastIndexOf("press"));
    scoreData=scoreData.split("\n");
    let musicData="";
    scoreData.forEach(e => {
        e=e.substring(0,e.indexOf(")")+1);
        if (e.length<8) {
            for (let i = 0; i < funArray.length; i++) {
                if (e.indexOf(funArray[i])!=-1) {
                    musicData+=(i+1)+" ";
                }
            }
        } else if(e.indexOf("sleep")>-1){
            musicData+=parseInt(e.substring(e.indexOf("(")+1,e.indexOf(")")))+"ms ";
        } else{
            console.log("未定义的数据："+e);
        }
    });
    return musicData;
}


function analysis(dataArray) {
    if (Array.isArray(dataArray)) {
        if (dataArray.length>1) {
            let i = 0;       
            let timeID=null; 
            let str="";      
            let startDelay=0;
            let delayTotal=0;
            timeID=setInterval(function(){
                startDelay+=delayDefault;
                if (i < dataArray.length) {
                    str=dataArray[i].toString();
                    if(logPrint) console.log("定时："+delayTotal+"ms"); 
                    if (str.length <= 2) {
                        
                        if (str!="" && str<=16 && str>0) {
                            let a=str;
                            anyData+=" "+str;
                            setTimeout(function(){run(a);},delayTotal);
                        }
                    }else {
                        if (str.substring(str.length-2)=="ms") {
                            str=str.substring(0,str.length-2);
                            anyData+=" "+str+"ms";
                            delayTotal+=parseInt(str);
                        }else if(dataArray[i].split(/[,，]/).length>1) {
                            var t=dataArray[i].split(/[,，]/);
                            if(logPrint) console.log("多点触碰"+t+"定时："+delayTotal);
                            anyData+=" "+t;
                            for(var j=0; j<t.length;j++){
                                
                                if (t[j]!="" && t[j]<=16 && t[j]>0) {
                                    let tempNum=t[j];
                                    setTimeout(function(){ run(tempNum);},delayTotal);
                                }
                            }
                        }
                    }
                    i++;
                } else {
                    if (tag) {
                        anyData+="\"}";
                    }
                    document.getElementById("anyData").value=anyData;
                    anyData="";
                    timeID=window.clearInterval(timeID);
                    
                    delayTotal-=startDelay;
                    document.getElementById("start").value="时长："+parseInt(delayTotal/1000)+"s";
                    timeID=setInterval(function(){
                        delayTotal-=1000;
                        document.getElementById("start").value="时长："+parseInt(delayTotal/1000)+"s";
                        if (delayTotal<0) {
                            document.getElementById("start").value="启动";
                            timeID=window.clearInterval(timeID);
                        }
                    },1000);
                }
            },delayDefault);
        }else{
            console.log("空数组");
        }
    }else{
        console.log("传入的对象不是数组"+dataArray);
    }
}


function run(key) {  
    if(key==undefined) return false;
    switch (key.toString()) {
        case  "1":    document.getElementById("m1").click();  break;
        case  "2":    document.getElementById("m2").click();  break;
        case  "3":    document.getElementById("m3").click();  break;
        case  "4":    document.getElementById("m4").click();  break;
        case  "5":    document.getElementById("m5").click();  break;
        case  "6":    document.getElementById("m6").click();  break;
        case  "7":    document.getElementById("m7").click();  break;
        case  "8":    document.getElementById("m8").click();  break;
        case  "9":    document.getElementById("m9").click();  break;
        case "10":    document.getElementById("m10").click(); break;
        case "11":    document.getElementById("m11").click(); break;
        case "12":    document.getElementById("m12").click(); break;
        case "13":    document.getElementById("m13").click(); break;
        case "14":    document.getElementById("m14").click(); break;
        case "15":    document.getElementById("m15").click(); break;
        default:if(logPrint) console.log("默认操作...未进行任何操作");break;
    }
}

function exec(Element) {
    let audio = document.getElementById("a"+Element.id);
    audio.currentTime = 0;
    audio.play();
    dieOut(Element);
}

function changeAny() {
    if (anyWay<0 || anyWay>=maxAny) {
        anyWay=0;
    } else {
        anyWay++;
    }
    f5AnyTip();
}
function f5AnyTip() {
    let str="";
    switch (anyWay) {
        case 1: str="score模式，识别score文件的格式";break;
        case 2: str="LiPu模式，识别离谱js文件的格式";break;
        default:str="普通模式，识别自己的格式";break;
    }
    document.getElementById("anyTip").innerText=str;
}

function changeWav() {
    if (wavWay<0 || wavWay>=maxWav) {
        wavWay=0;
    } else {
        wavWay++;
    }
    let audios=document.getElementById("wavPlayer").getElementsByTagName("audio");
    for (let i = 0; i < audios.length; i++) {
        if (!audios[i].paused) {
            audios[i].pause();
        }
    }
    f5WavTip();
}

/**
 * 
 * @param {Int} delay 
 * @param {Function} fun 
 */
function sleep(delay, fun) {
    let int=window.setInterval(function(){
        fun();
        clearInterval(int);
    },delay);
}

function sleepFor(delay,startNum,endNum,addNum,fun,startFun) {
    
    let int=window.setInterval(function(){
        if (startNum<endNum) {
            fun();
            startNum+=addNum;
        } else {
            startFun();
            clearInterval(int);
        }
    },delay);
}

function readFile(file) {
    let t=document.getElementById("fileTip");
    if (file != undefined) {
        t.innerText="读取中...";
        let read = new FileReader();
        read.readAsText(file, "UTF-8");
        read.onload = function(ProgressEvent){
            t.innerText="读取完成";
            if(removeText) document.getElementById("data").value="";
            document.getElementById("data").value+=ProgressEvent.target.result;
            setTimeout(function(){t.innerText="";},3000);
        }
    } else {
        t.innerText="文件不存在!";
    }
}

function isFile() {
    let file=document.getElementById("fileId");
    if (file.value == "") {
        document.getElementById("fileTip").innerText="没有文件";
    } else {
        readFile(file.files[0]);
    }
    setTimeout(function(){  document.getElementById("fileTip").innerText="" },3000);
}
function setDelay(){
    let inputDelay = document.getElementById("delay");
    delayDefault=inputDelay.value;
    inputDelay.value=delayDefault;
}

function setVolumeNum(param) {
    let audios=document.getElementById("wavPlayer").getElementsByTagName("audio");
    volume=param!=undefined?param:volume;
    if (volume) {
        for (let i = 0; i < audios.length; i++) {
            audios[i].volume=0;
        }
        volume=false;
        document.getElementById("setvolume").value="音量X";
    }else{
        for (let i = 0; i < audios.length; i++) {
            audios[i].volume=1;
        }
        volume=true;
        document.getElementById("setvolume").value="音量√";
    }
}
function setRemoveText(param){
    if(param==null) param=!removeText;
    removeText=param;
    document.getElementById("removeText").value=removeText?"读取文件时清除上面的文本框√":"读取文件时清除上面的文本框×";
}
function showL() {
    let div=document.getElementById("L").style;
    let fillDiv=document.getElementById("Lfill");
    if(div.display=="none"){
        div.display="inline";
        fillDiv.style.height="0rem";
        fillDiv.onclick="";
    }else{
        div.display="none";
        fillDiv.style.height="6rem";
        fillDiv.onclick=function(){showL()};
    }

}